package com.bw.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.aop.Log;
import com.bw.domain.Users;
import com.bw.service.UsersService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UsersService usersService;

    @Autowired
    RedisTemplate redisTemplate;


   @RequestMapping("login")
    public Result login(@RequestBody Users users) {
        String s=(String) redisTemplate.opsForValue().get(users.getUuid());
        if(!s.equals(users.getCode())){
            return Result.fail("验证码错误");
        }
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUsername,users.getUsername());
        Users one = usersService.getOne(wrapper);
        if(one==null){
            return Result.fail("用户名错误");
        }
        String s1 = DigestUtil.md5Hex(users.getPassword() + salt);
        if(!one.getPassword().equals(s1)){
            return Result.fail("密码错误");
        }
        String token = JWTUtils.createToken(one.getUsername(), 60 * 12);
        return Result.success(token);

    }
    public static final String salt="2108A";
    @RequestMapping("code")
    public Result code(){
        String pwd="123";
        String s = DigestUtil.md5Hex(pwd + salt);
        return Result.success(s);
    }

   @RequestMapping("createcode")
    public void createscode(String uuid, HttpServletResponse response) throws IOException {
       CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
     captcha.write(response.getOutputStream());
     redisTemplate.opsForValue().set(uuid,captcha.getCode(),5,TimeUnit.MINUTES);
   }
























}
